﻿using ConsoleApplication.WebAPI;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HM
{
    [HotUpdate]
    [Description("判断出入库流水从直接调拨下推销售出库")]
    public class DBPushCk : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            try
            {
                var result = InvokeHelper.Login();
                var iResult = JObject.Parse(result)["LoginResultType"].Value<int>();
                string MATERILA = "", F_RXWU_Text2 = "", FDATE = "", DBFEnteyID = "";
                if (iResult == 1)
                {
                    string SQL = "/*dialect*/" + string.Format(@"select T10.FNUMBER MATERILA,T.F_RXWU_Text2,T.FDATE,t1.FEntryID DBFEnteyID
                            from T_STK_STKTRANSFERIN t
                            left join T_STK_STKTRANSFERINENTRY t1 on t.fid=t1.fid
                            Left join T_BD_MATERIAL t10 on t1.FMATERIALID=t10.FMATERIALID
							left join T_STK_STKTRANSFERINENTRY_R t3 on t1.FENTRYID=t3.FENTRYID
                            where FBizType<>'DRPTRANS'
							and t1.F_RXWU_QTY2=0 and t.F_RXWU_Text2<>''");
                    DynamicObjectCollection DynamData = DBUtils.ExecuteDynamicObject(ctx, SQL);
                    if (DynamData.Count > 0)
                    {
                        for (int i = 0; i < DynamData.Count; i++)
                        {
                            MATERILA = Convert.ToString(DynamData[i]["MATERILA"]);
                            F_RXWU_Text2 = Convert.ToString(DynamData[i]["F_RXWU_Text2"]);
                            FDATE = Convert.ToString(DynamData[i]["FDATE"]);
                            DBFEnteyID = Convert.ToString(DynamData[i]["DBFEnteyID"]);
                            //3.1没有退货，有核销状态的普通订单直接推销售出库
                            ///条件1：物料编码+平台单号，在出入库流水明细没有找到单据类型=销售退货，///条件2：调拨单日期 + 物料编码 + 平台单号，对应的核销状态AutoCheck或UserCheck条件3：订单类型 = 普通订单
                            string SQL0 = "/*dialect*/" + string.Format(@"select T1.F_RXWU_Date2,T1.FEntryId,T1.F_RXWU_Date from RXWU_t_Cust100002 t
							left join RXWU_t_Cust_Entry100013 t1 on t.FID=t1.FID
							left join T_BD_MATERIAL t2 on t1.FMATERIALID=t2.FMATERIALID
							WHERE T1.F_RXWU_Text6 not in (select t1.F_RXWU_Text6 from RXWU_t_Cust100002 t
							left join RXWU_t_Cust_Entry100013 t1 on t.FID=t1.FID
							where t1.F_RXWU_Text2='销售退货') 
							and (T1.F_RXWU_TEXT15='AutoCheck'OR T1.F_RXWU_TEXT15='UserCheck')  AND t1.F_RXWU_Text2='销售出仓' AND t1.F_RXWU_Text16='普通订单'
                            AND  t1.F_RXWU_Date2>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)
                            AND T1.F_RXWU_Text6='{0}' AND T2.FNUMBER='{1}' AND T1.F_RXWU_DATE='{2}'", F_RXWU_Text2, MATERILA, FDATE);
                            DynamicObjectCollection DynamData0 = DBUtils.ExecuteDynamicObject(ctx, SQL0);
                            if (DynamData0.Count > 0)
                            {
                                string F_RXWU_Date2 = "", FEntryId = "", F_RXWU_Date = "";
                                FEntryId = Convert.ToString(DynamData0[0]["FEntryId"]);
                                F_RXWU_Date2 = Convert.ToString(DynamData0[0]["F_RXWU_Date2"]);
                                F_RXWU_Date = Convert.ToString(DynamData0[0]["F_RXWU_Date"]);
                                string json = "{\"Ids\":\"\",\"Numbers\":[],\"EntryIds\":\"" + DBFEnteyID + "\",\"RuleId\":\"TransferDirect-OUTSTOCK\",\"TargetBillTypeId\":\"\",\"TargetOrgId\":0,\"TargetFormId\":\"SAL_OUTSTOCK\",\"IsEnableDefaultRule\":\"false\",\"IsDraftWhenSaveFail\":\"false\",\"CustomParams\":{}}";
                                result = InvokeHelper.Push("STK_TransferDirect", json.ToString());
                                JObject jobject = JObject.Parse(result);
                                string a = Convert.ToString(jobject["Result"]["ResponseStatus"]["IsSuccess"]);
                                bool IsSuccess = a == "True";
                                if (IsSuccess)
                                {
                                    string SQL3 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='1' where FEntryId='{0}'", FEntryId);
                                    DBUtils.Execute(ctx, SQL3);
                                    Log.WriteLog("直接调拨单自动下推销售出库单成功", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                    var SuccessEntitysId = jobject["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"];
                                    string SQL4 = "/*dialect*/" + string.Format(@"update T_SAL_OUTSTOCK set FDATE='{1}' where FID='{0}'", SuccessEntitysId, F_RXWU_Date2);
                                    DBUtils.Execute(ctx, SQL4);
                                    string Submit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"SelectedPostId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                    result = InvokeHelper.Submit("SAL_OUTSTOCK", Submit);
                                    string Audit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"InterationFlags\":\"\",\"NetworkCtrl\":\"\",\"IsVerifyProcInst\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                    result = InvokeHelper.Audit("SAL_OUTSTOCK", Audit);
                                }
                                else
                                {
                                    Log.WriteLog("直接调拨单自动下推销售出库单失败", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                    string SQL3 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='0' where FEntryId='{0}'", FEntryId);
                                    DBUtils.Execute(ctx, SQL3);
                                }
                            }
                            //3.2，订单类型=补发或者换货，直接推销售出库
                            ///条件1：物料编码+平台单号，在出入库流水明细没有找到单据类型=销售退货，条件2：调拨单日期 + 物料编码 + 平台单号，订单类型 = 补发订单或者换货订单，
                            string SQL1 = "/*dialect*/" + string.Format(@"select T1.F_RXWU_Date2,T1.FEntryId,T1.F_RXWU_Date from RXWU_t_Cust100002 t
							left join RXWU_t_Cust_Entry100013 t1 on t.FID=t1.FID
							left join T_BD_MATERIAL t2 on t1.FMATERIALID=t2.FMATERIALID
							WHERE (t1.F_RXWU_Text16='补发订单'
                            OR t1.F_RXWU_Text16='换货订单') 
                            AND T1.F_RXWU_DATE>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)
                            AND T1.F_RXWU_Text6='{0}' AND T2.FNUMBER='{1}' AND T1.F_RXWU_DATE='{2}'", F_RXWU_Text2, MATERILA, FDATE);
                            DynamicObjectCollection DynamData1 = DBUtils.ExecuteDynamicObject(ctx, SQL1);
                            if (DynamData1.Count > 0)
                            {
                                string F_RXWU_Date2 = "", FEntryId = "", F_RXWU_Date = "";
                                FEntryId = Convert.ToString(DynamData1[0]["FEntryId"]);
                                F_RXWU_Date2 = Convert.ToString(DynamData1[0]["F_RXWU_Date2"]);
                                F_RXWU_Date = Convert.ToString(DynamData1[0]["F_RXWU_Date"]);
                                string json = "{\"Ids\":\"\",\"Numbers\":[],\"EntryIds\":\"" + DBFEnteyID + "\",\"RuleId\":\"TransferDirect-OUTSTOCK\",\"TargetBillTypeId\":\"\",\"TargetOrgId\":0,\"TargetFormId\":\"SAL_OUTSTOCK\",\"IsEnableDefaultRule\":\"false\",\"IsDraftWhenSaveFail\":\"false\",\"CustomParams\":{}}";
                                result = InvokeHelper.Push("STK_TransferDirect", json.ToString());
                                JObject jobject = JObject.Parse(result);
                                string a = Convert.ToString(jobject["Result"]["ResponseStatus"]["IsSuccess"]);
                                bool IsSuccess = a == "True";
                                if (IsSuccess)
                                {
                                    string SQL3 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='1' where FEntryId='{0}'", FEntryId);
                                    DBUtils.Execute(ctx, SQL3);
                                    Log.WriteLog("直接调拨单自动下推销售出库单成功", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                    var SuccessEntitysId = jobject["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"];
                                    string SQL4 = "/*dialect*/" + string.Format(@"update T_SAL_OUTSTOCK set FDATE='{1}' where FID='{0}'", SuccessEntitysId, F_RXWU_Date);
                                    DBUtils.Execute(ctx, SQL4);
                                    string Submit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"SelectedPostId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                    result = InvokeHelper.Submit("SAL_OUTSTOCK", Submit);
                                    string Audit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"InterationFlags\":\"\",\"NetworkCtrl\":\"\",\"IsVerifyProcInst\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                    result = InvokeHelper.Audit("SAL_OUTSTOCK", Audit);
                                }
                                else
                                {
                                    Log.WriteLog("直接调拨单自动下推销售出库单失败", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                    string SQL3 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='0' where FEntryId='{0}'", FEntryId);
                                    DBUtils.Execute(ctx, SQL3);
                                }
                            }
                            //3.3有退货，推销售出库
                            ///条件1：物料编码 + 平台单号，在出入库流水明细找到单据类型 = 销售退货，条件2：当物料编码 + 平台单号对应，退货日期 >= 到账时间，订单类型 = 普通订单条件3：调拨单日期 + 物料编码 + 平台单号，对应的核销状态AutoCheck或UserCheck
                            string SQL2 = "/*dialect*/" + string.Format(@"select T1.F_RXWU_Date2,T1.FEntryId,T1.F_RXWU_Date from RXWU_t_Cust100002 t
							left join RXWU_t_Cust_Entry100013 t1 on t.FID=t1.FID
							left join T_BD_MATERIAL t2 on t1.FMATERIALID=t2.FMATERIALID
                            left join (
					        select b.F_RXWU_Text6,b.FMATERIALID,a.FDATE from RXWU_t_Cust100002 a
					        left join RXWU_t_Cust_Entry100013 b on a.FID=b.FID
					        where b.F_RXWU_Text2='销售退货'
					        ) t11 on t1.F_RXWU_Text6=t11.F_RXWU_Text6 and t1.FMATERIALID=t11.FMATERIALID
							WHERE T1.F_RXWU_Text6  in (select t1.F_RXWU_Text6 from RXWU_t_Cust100002 t
							left join RXWU_t_Cust_Entry100013 t1 on t.FID=t1.FID
							where t1.F_RXWU_Text2='销售退货') 
							and (T1.F_RXWU_TEXT15='AutoCheck'OR T1.F_RXWU_TEXT15='UserCheck')  AND t1.F_RXWU_Text2='销售出仓' AND t1.F_RXWU_Text16='普通订单'
                            AND  t1.F_RXWU_Date2>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)
                            and t.FDATE>=T1.F_RXWU_DATE2
                            AND T1.F_RXWU_Text6='{0}' AND T2.FNUMBER='{1}' AND T1.F_RXWU_DATE='{2}'", F_RXWU_Text2, MATERILA, FDATE);
                            DynamicObjectCollection DynamData2 = DBUtils.ExecuteDynamicObject(ctx, SQL2);
                            if (DynamData2.Count > 0)
                            {
                                string F_RXWU_Date2 = "", FEntryId = "", F_RXWU_Date = "";
                                FEntryId = Convert.ToString(DynamData2[0]["FEntryId"]);
                                F_RXWU_Date2 = Convert.ToString(DynamData2[0]["F_RXWU_Date2"]);
                                F_RXWU_Date = Convert.ToString(DynamData2[0]["F_RXWU_Date"]);
                                string json = "{\"Ids\":\"\",\"Numbers\":[],\"EntryIds\":\"" + DBFEnteyID + "\",\"RuleId\":\"TransferDirect-OUTSTOCK\",\"TargetBillTypeId\":\"\",\"TargetOrgId\":0,\"TargetFormId\":\"SAL_OUTSTOCK\",\"IsEnableDefaultRule\":\"false\",\"IsDraftWhenSaveFail\":\"false\",\"CustomParams\":{}}";
                                result = InvokeHelper.Push("STK_TransferDirect", json.ToString());
                                JObject jobject = JObject.Parse(result);
                                string a = Convert.ToString(jobject["Result"]["ResponseStatus"]["IsSuccess"]);
                                bool IsSuccess = a == "True";
                                if (IsSuccess)
                                {
                                    string SQL3 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='1' where FEntryId='{0}'", FEntryId);
                                    DBUtils.Execute(ctx, SQL3);
                                    Log.WriteLog("直接调拨单自动下推销售出库单成功", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                    var SuccessEntitysId = jobject["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"];
                                    string SQL4 = "/*dialect*/" + string.Format(@"update T_SAL_OUTSTOCK set FDATE='{1}' where FID='{0}'", SuccessEntitysId, F_RXWU_Date2);
                                    DBUtils.Execute(ctx, SQL4);
                                    string Submit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"SelectedPostId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                    result = InvokeHelper.Submit("SAL_OUTSTOCK", Submit);
                                    string Audit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"InterationFlags\":\"\",\"NetworkCtrl\":\"\",\"IsVerifyProcInst\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                    result = InvokeHelper.Audit("SAL_OUTSTOCK", Audit);
                                }
                                else
                                {
                                    Log.WriteLog("直接调拨单自动下推销售出库单失败", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                    string SQL3 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='0' where FEntryId='{0}'", FEntryId);
                                    DBUtils.Execute(ctx, SQL3);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("直接调拨单自动下推销售出库单程序报错", "原因:" + ex.ToString() + "ctx:" + ctx);
            } 
        }
    }
}
